<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品状态" prop="productFlag">
        <el-select v-model="queryParams.productFlag" placeholder="请选择商品状态" clearable>
          <el-option v-for="dict in dict.type.product_flag" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品标题" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入商品标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="店铺名称" prop="storeName">
        <el-input v-model="queryParams.storeName" placeholder="请输入店铺名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品编号" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入商品编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="shopAdd"
          v-hasPermi="['store:productinfo:releaseList']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['store:productinfo:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="productinfoList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="商品编号" align="left" prop="productCode" />
      <el-table-column label="店铺名称" align="left" prop="storeName" />
      <el-table-column label="商品名称" align="left" prop="storeName" width="280">
        <template slot-scope="scope">
          <div style="display: flex;">
            <div style="width: 100px;height: 100px;">
              <el-image style="width: 100px; height: 100px" :src="scope.row.productManUrl" fit="contain"></el-image>
            </div>
            <div
              style="width: 180px;display: flex;flex-direction:column;justify-content: center;padding-left: 10px;box-sizing: border-box;">
              <div>
                <el-tooltip class="item" effect="dark" placement="top" :content="scope.row.productName">
                  <div class="cell-ellipsis">{{ scope.row.productName }}</div>
                </el-tooltip>
              </div>
              <div><el-tooltip class="item" effect="dark" placement="top" :content="scope.row.specification">
                  <div class="cell-ellipsis">{{ scope.row.specification }}</div>
                </el-tooltip></div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品金额" align="left" prop="productShowPrice">
      </el-table-column>
      <el-table-column label="库存" align="left" prop="productNumber">
      </el-table-column>
      <el-table-column label="累计销售数" align="left" prop="saleSort">
      </el-table-column>
      <el-table-column label="商品状态" align="center" prop="productFlag">
        <template slot-scope="scope">
          <el-tag size="medium" :type="scope.row.productFlag === '1' ? 'success' : 'info'">
            <dict-tag :options="dict.type.product_flag" :value="scope.row.productFlag" />
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="left" prop="crTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.crTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="220" label="操作" align="center" class-name="small-padding fixed-width">
        <!-- 权限 -->
        <template slot-scope="scope">
          <!-- v-hasPermi="['store:productinfo:edit']" -->
          <el-popconfirm title="确定要上架此商品吗？" @confirm="groundConfirm(scope.row)">
            <el-button slot="reference" v-if="scope.row.productFlag && scope.row.productFlag==='2'" size="mini"
              type="text">上架</el-button>
          </el-popconfirm>
          <el-popconfirm title="确定要下架此商品吗？" @confirm="underConfirm(scope.row)">
            <el-button slot="reference" v-if="scope.row.productFlag && scope.row.productFlag==='1'" size="mini"
              type="text">下架</el-button>
          </el-popconfirm>
          <!-- v-hasPermi="['system:user:resetPwd', 'system:user:edit']" -->
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleResetPwd">基本信息编辑</el-dropdown-item>
              <el-dropdown-item command="handleAuthRole">规格编辑</el-dropdown-item>
              <el-dropdown-item command="handleAuthRole">商品图片编辑</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>

<script>
  import {
    fileDeleteOss
  } from "@/api/system/user";

  import {
    getProductinfo,
    getinventorylist,
    getProductinfoNew,
    productCodeEditDetails
  } from "@/api/store/productinfo";

  export default {
    name: "Productinfo",
    dicts: ['product_flag'],
    data() {
      return {
        groundVisible: false, //上架
        offShelfVisible: false, //下架
        nestedTableData: [],
        dictArr: [{
            value: '0',
            label: '未生效'
          },
          {
            value: '1',
            label: '已生效'
          }
        ],
        tableData: [],
        editForm: {},
        dialogVisible: false,
        dialogTitle: '',
        tabPosition: 'left',
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 商品类目表格数据
        productinfoList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          storeCode: null,
          productName: null,
          productManUrl: null,
          salePrice: null,
          purchasePrice: null,
          specification: null,
          productDescription: null,
          couponFlag: null,
          couponMax: null,
          provinceId: null,
          cityId: null,
          countyId: null,
          productFlag: null,
          productFrom: null,
          fromAddress: null,
          productStory: null,
          hotSort: null,
          saleSort: null,
          ratingNumb: null,
          crTime: null,
          upTime: null,
          backProvinceId: null,
          backCityId: null,
          backCountyId: null,
          backFrom: null,
          returnUser: null,
          returnPhone: null,
          receiveUser: null,
          receivePhone: null
        },
        // 表单参数
        form: {},
        xlsFile: [],
        fileListN: [],
        listNew: [],
        xlsFile1: [],
        fileListN1: [],
        listNew1: [],
        // 表单校验
        rules: {},
        allList: [],

        addressXz: [],
        propsObj: {
          label: 'text',
          value: 'value',
          option: 'children',
        },
        pastInventoryList: [],
        pastProductInfo: {},
        // 修改的
        updateInventoryList: [],
        // 新增的
        insertInventoryList: [],
        inventoryIdids: [],
        viewDialogVisible: false,
        viewGgData: []
      };
    },
    created() {
      this.getProductinfoNew()
    },
    methods: {
      getList() {

      },
      // 0929 start
      getProductinfoNew() {
        let params = {
          storeName: '',
          productCode: '',
          productFlag: '',
          productName: '',
        }
        // 回显规格接口
        getProductinfoNew(params).then(response => {
          console.log(response, 'response11111')
          if (response.code == '200') {
            this.productinfoList = response.data;
            this.total = response.total;
            this.loading = false;
          }
        });
      },

      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "handleResetPwd":
            this.handleResetPwd(row);
            break;
          case "handleAuthRole":
            this.handleAuthRole(row);
            break;
          default:
            break;
        }
      },


      /** 重置密码按钮操作 */
      handleResetPwd(row) {
        // this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        //   confirmButtonText: "确定",
        //   cancelButtonText: "取消",
        //   closeOnClickModal: false,
        //   inputPattern: /^.{5,20}$/,
        //   inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        //   inputValidator: (value) => {
        //     if (/<|>|"|'|\||\\/.test(value)) {
        //       return "不能包含非法字符：< > \" ' \\\ |"
        //     }
        //   },
        // }).then(({ value }) => {
        //     resetUserPwd(row.userId, value).then(response => {
        //       this.$modal.msgSuccess("修改成功，新密码是：" + value);
        //     });
        //   }).catch(() => {});
      },


      /** 分配角色操作 */
      handleAuthRole: function(row) {
        const userId = row.userId;
        // this.$router.push("/system/user-auth/role/" + userId);
      },

      // 上架
      groundConfirm(row) {
        let params = {
          pastInventoryList: [{
            inventoryId: row.specification,
            productFlag: '1', //上架1   下架0
          }]
        }
        // 回显规格接口
        productCodeEditDetails(params).then(response => {
          console.log(response, 'response11111')
          if (response.code == '200') {
            // this.productinfoList = response.data;
            // this.total = response.total;
            // this.loading = false;
          }
        });
        console.log('上架', row)
      },

      // 下架
      underConfirm(row) {
        console.log('下架', row)
      },

      shopAdd() {
        console.log('跳转这个1111111')
        this.$router.push("/productinfoDetails");
      },
      shopEdit(row) {
        const productCode = row.productCode;
        this.$router.push("/productinfoDetails");
      },
      deleteImage(index) {
        let res = this.listNew[index].url
        const data = {
          'fileName': res
        }
        fileDeleteOss(data).then(response => {
          if (response.code == '200') {
            this.listNew.splice(index, 1)
            this.$modal.msgSuccess("删除成功");
          }
        });
      },
      handleExceedN() {},
      // 身份证反面

      handlePreviewNun() {},
      handleRemoveNun() {},
      beforeRemoveNun() {},
      fileChangeun(file, fileList) {
        console.log(fileList, '============')
        this.xlsFile1 = fileList
      },
      handle_successNun(res) {
        console.log('图片上传成功')
      },
      handleExceedNun() {},
      handleAddGg() {
        this.dialogVisible = true;
        this.dialogTitle = '新增';
        this.editForm = {}; // 清空表单
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          storeCode: null,
          productName: null,
          productManUrl: null,
          productShowPrice: null,
          productFlag: null,
          provinceId: null,
          cityId: null,
          countyId: null,
          productFrom: null,
          hotSort: null,
          fromAddress: null,
          productStory: null,
          saleSort: null,
          productDescription: null,
          backProvinceId: null,
          backCityId: null,
          backCountyId: null,
          backFrom: null,
          returnUser: null,
          returnPhone: null,
          receiveUser: null,
          receivePhone: null
        };
        this.resetForm("form");
        this.xlsFile = [];
        this.fileListN = [];
        this.listNew = [];
        this.tableData = []

      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getProductinfoNew();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.productCode)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加商品类目";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const productCode = row.productCode || this.ids
        // 回显规格接口
        getinventorylist(row.productCode).then(response => {
          if (response.code == '200') {
            this.tableData = response.data
            this.pastInventoryList = JSON.parse(JSON.stringify(response.data))
          }
        });
        //  回显基本信息
        getProductinfo(productCode).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改商品类目";
          this.listNew.push({
            url: this.form.productManUrl
          })
          // this.listNew1.push({url:this.form.legalPersonPicReverse})
          this.form.provinceCityCountry = [this.form.provinceId, this.form.cityId, this.form.countyId]
          this.form.backProvinceCityCountry = [this.form.backProvinceId, this.form.backCityId, this.form
            .backCountyId
          ]
          this.pastProductInfo = JSON.parse(JSON.stringify(response.data))
        });
        // 修改的
        this.updateInventoryList = [],
          // 新增的
          this.insertInventoryList = []
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('store/productinfo/export', {
          ...this.queryParams
        }, `productinfo_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
<style>
  .cell-ellipsis {
    width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    text-align: left;
  }

  .multi-line-text {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    /* 显示的行数 */
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: normal;
    max-height: 3.0em;
    /* 行高和这个值相乘就是最大高度 */
  }

  .image-list {
    list-style-type: none;
    margin: 0px;
    padding: 0px;
    display: flex;
    flex-wrap: wrap;

    li {
      width: 150px;
      height: 150px;
      margin-right: 3%;
      position: relative;

      span {
        position: absolute;
        right: 0px;
        top: 0px;
        cursor: pointer;
      }
    }
  }
</style>
